// merchant//merchants/receFuli/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    cardItemId: 0,
    defaultBalance: 0,
  },

  receFuli: function (e) {
    let that = this;
    let code = that.data.code;
    
    if (!code) {
      wx.showToast({
        title: '请输入授权码',
      })
      return;
    }
    if (!e.detail.encryptedData) {
      wx.showToast({
        title: '请先授权手机号',
        duration: 1500
      })
      return;
    }
    wx.login({
      success: function (res) {
        var loginCode = res.code;
        wx.request({
          url: app.globalData.host + '/api/account/getphonenumber?encryptedData=' + encodeURIComponent(e.detail.encryptedData) + '&iv=' + encodeURIComponent(e.detail.iv) + '&storeid=' + app.globalData.storeId + '&storeAppId=' + app.globalData.storeAppId + "&code=" + loginCode,
          success: function (res) {
            if (res.data.Code == 0) {
              app.globalData.userInfo.Mobile = res.data.Data;
              wx.setStorageSync("mobile", res.data.Data);
              wx.request({
                url: app.globalData.host + '/api/coupon/ReceiveCardItem',
                data: {
                  uid: app.globalData.userInfo.Uid,
                  cardItemId: that.data.cardItemId,
                  code: code
                },
                method: 'POST',
                success: function (res) {
                  if (res.data.Code == 0) {
                    wx.showToast({
                      title: '领取成功',
                    })
                    setTimeout(function () {
                      wx.reLaunch({
                        url: '/merchant/merchants/myCardCoupon/index',
                      })
                    }, 1500)
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: res.data.Message,
                      showCancel: false
                    })
                  }
                }
              })
            } else {
              wx.showToast({
                title: '手机号授权失败',
              })
            }
          },
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options) {
      this.data.cardId = options.cardId;
      wx.setStorageSync('cardId', options.cardId);
      this.data.cardItemId = options.cardItemId;
      this.getUserCard(options.cardItemId);
    }
  },

  getUserCard: function (cardItemId) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardItem?id=' + cardItemId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            defaultBalance: res.data.Data.DefaultBalance
          })
        }
      }
    })
  },

  bindCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  }

})